package data.factory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import tools.Pair;
import data.set.OfflineSet;
import data.set.implementation.OfflineSet_Memory;
import data.vectors.DoubleVector;
import data.vectors.implementation.DoubleVector_Sparse_Memory;

public class NumericalOfflineSetFromOctaveFile {
	private String path, pathLabel;
	

	public NumericalOfflineSetFromOctaveFile(String path, String pathLabel){
		this.path = path;
		this.pathLabel = pathLabel;
	}
	
	public NumericalOfflineSetFromOctaveFile(String path){
		this.path = path;
		this.pathLabel = null;
	}

	public Pair< OfflineSet<DoubleVector>, OfflineSet<Integer>> build(){
		OfflineSet_Memory<DoubleVector> bd = new OfflineSet_Memory<DoubleVector>(); 
		OfflineSet_Memory<Integer> labels = new OfflineSet_Memory<Integer>();
		
		try{
			String filename = path;
			FileReader fr = new FileReader(new File(filename));
			BufferedReader in = new BufferedReader(fr);

			String str;
			while(true){
				str = in.readLine();
				if (!str.startsWith("#"))
					break;
			}
			while(str!=null){
				String[] ss =  str.split("[\\s]+");
				int idFeature = Integer.valueOf(ss[0]);
				int idDoc = Integer.valueOf(ss[1]);
				double count = Double.valueOf(ss[2]);
				
				DoubleVector_Sparse_Memory vec = (DoubleVector_Sparse_Memory) bd.getObject(idDoc);
				if (vec==null){
					vec = new DoubleVector_Sparse_Memory();
					bd.add(idDoc, vec);
				}
				vec.setValue(idFeature, count);
				
				str = in.readLine();
			}
			in.close();
	        
	        //------------------------------------------
			filename = pathLabel;
			if(filename == null)
				return new Pair<OfflineSet<DoubleVector>,OfflineSet<Integer>>(bd,null);
				
			fr = new FileReader(new File(filename));
			in = new BufferedReader(fr);

			while(true){
				str = in.readLine();
				if (!str.startsWith("#"))
					break;
			}
			while(str!=null){
				String[] ss =  str.split("[\\s]+");
				int idDoc = Integer.valueOf(ss[0]);
				int label = Integer.valueOf(ss[1]);
				
				labels.add(idDoc, label);
				
				str = in.readLine();
			}
			in.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return new Pair<OfflineSet<DoubleVector>,OfflineSet<Integer>>(bd,labels);
	}
}
